var sc_process_vars = {
		"po_recd_status" : null,
		"inv_sent_status" : null,
		"cm_sent_status" : null,
		"pmt_recd_status" : null
};

var sc_pvar_int = null;

jQuery(document).ready(function() {
		//
		init_poreceived();
		init_invsent();
		init_cmemosent();
		init_pmtreceived();
		var d = new Date();
		var s2 = format_date(d);
		d.setDate(d.getDate() - 7)
		var s1 = format_date(d);
		dwr.util.setValue('sc_last_seven', s1 + ' - ' + s2);
		init_supplier_main();
		
		clearInterval(sc_pvar_int);
		sc_pvar_int = null;
		sc_pvar_int = setInterval(sc_check_initprocesses,2000);
	});

function sc_check_initprocesses(){
	if(!isEmptyString(sc_process_vars.po_recd_status)
			&& !isEmptyString(sc_process_vars.inv_sent_status)
			&& !isEmptyString(sc_process_vars.cm_sent_status)
			&& !isEmptyString(sc_process_vars.pmt_recd_status)){
		jQuery('#sc_activity_throbber').removeClass('throbberOn').addClass('throbberOff');
		clearInterval(sc_pvar_int);
		sc_pvar_int = null;
	}
	
	//Check for errors on individual statuses
}
	
	function init_supplier_main(){

		//Show PO Sent as default for buyer context
		jQuery('#sc_po_recd_a').removeClass('showlist');
		jQuery('#sc_po_recd_a').addClass('hide');
		jQuery('#sc_po_recd_sp').removeClass('hide');
		jQuery('#sc_po_recd_sp').addClass('showlist visitedbold');
		jQuery('#ctx_sc_po_recd_tbldiv').removeClass('hide');
		jQuery('#ctx_sc_po_recd_tbldiv').addClass('show');
		jQuery('#sc_activity_throbber').removeClass('throbberOff').addClass('throbberOn');
		dwr.util.removeAllRows("sc_notifications_body", {filter:function (tr) {return (tr.id != "sc_notifications_pattern");}});
		poreceived_cache = [];
		
		render_jqportable();
		
		//Reset notification header.
		dwr.util.setValue('sc_notifications_header','Loading messages...');
		jQuery('#sc_notifications_throbber').removeClass('notif_throbberOff').addClass('notif_throbberOn');
		
		//Get notifications.
		c_get_notifications(false);
	}

	function init_poreceived() {
		var dwrCallMetaData = {
			callback : success_findpobycompany,
			exceptionHandler : ysn_dwrerror_handler,
			timeout : 100000,
			errorHandler : ysn_dwrerror_handler
		};

		DWR_PurchaseOrders.fetchPurchaseOrdersForCompany(usrcompany_uid, false,
				true, dwrCallMetaData);
	}

	var poreceived_cache = [];
	function success_findpobycompany(dwrresp) {

		if (dwrresp && dwrresp.respCode == 0) {
			if (dwrresp.objRespOrError != null
					&& dwrresp.objRespOrError["PO_RECD"] != null
					&& dwrresp.objRespOrError["PO_RECD"].length > 0) {
				//orderAttachments
				poreceived_cache = dwrresp.objRespOrError["PO_RECD"];
				sc_process_vars.po_recd_status = "0";
			}else{
				poreceived_cache=[];
				sc_process_vars.po_recd_status = "1";
			}
			render_jqportable();
		}
	}
	
	var ctx_porecd_table = null;
	function render_jqportable() {
		if(ctx_porecd_table != null){
			ctx_porecd_table.fnDestroy();
			ctx_porecd_table = null;
		}
		ctx_porecd_table = jQuery('#ctx_sc_po_recd_tbl').dataTable({
			"bProcessing" : true,
			"aaData" : poreceived_cache,
			"bJQueryUI" : true,
			"bSortClasses" : false,
			"bRetrieve" : true, 
			"aoColumns" :  [ {
				"mDataProp" : "orderNumber",
				"sClass": "alignCenter",
				"fnRender" : function(obj) {
					var onum = obj.aData.orderNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "orderDate",
				"sType" : "date",
				"sClass": "alignCenter",
				"fnRender" : function(obj) {

					return format_date(obj.aData.orderDate);
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "clientNameText",
				"sClass": "alignCenter"
				
			}, {
				"mDataProp" : "orderAmount",
				"sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.orderAmount);
					
					return om;
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "invoicedAmount",
				"sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.invoicedAmount);
					
					return om;
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "poStatus",
				"sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = obj.aData.poStatus;
					
					if(isEmptyString(om) || om == G_STATUS_MAP["PO_STATUS_NEW"]){
						om = "Sent"
					}else if(om == G_STATUS_MAP["PO_STATUS_NEW"]){
						om = "Fully Invoiced";
					}else if(om == G_STATUS_MAP["PO_STATUS_FULLY_INVOICED"]){
						om = "Fully Invoiced";
					}else if(om == G_STATUS_MAP["PO_STATUS_PARTIALLY_INVOICED"]){
						om = "Partially Invoiced";
					}else if(om == G_STATUS_MAP["PO_STATUS_CANCELLED"]){
						om = "Cancelled";
					}else if(om == G_STATUS_MAP["PO_STATUS_FAILED"]){
						om = "Failed";
					}else {
						om = "Status not Available."
					}
					
					return om;
				},
				"bUseRendered" : false
			},{
				"mDataProp" : "orderOwner","sClass": "alignCenter"
			},{
				"mDataProp" : "versionNumber","sClass": "alignCenter"
			} ]
		});
	}

	function init_invsent() {

		var dwrCallMetaData = {
			callback : success_fetchinvoicesent,
			exceptionHandler : ysn_dwrerror_handler,
			timeout : 100000,
			errorHandler : ysn_dwrerror_handler
		};

		DWR_Invoice.fetchInvoicesSent(usrcomp_comapnyId, dwrCallMetaData);
	}

	var invsent_cache = null;

	function success_fetchinvoicesent(dwrresp) {

		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			invsent_cache = dwrresp.objRespOrError;
			sc_process_vars.inv_sent_status = "0";
		}else{
			invsent_cache = [];
			sc_process_vars.inv_sent_status = "1";
		}
		
		render_jqinvstable();
	}
	
	var ctx_invsent_table = null;
	function render_jqinvstable() {
		ctx_invsent_table = jQuery('#ctx_sc_inv_sent_tbl').dataTable({
			"bProcessing" : true,
			"aaData" : invsent_cache,
			"bJQueryUI" : true,
			"bSortClasses" : false,
			"aoColumns" : [ {
				"mDataProp" : "invoiceNumber","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var onum = obj.aData.invoiceNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "clientNameText","sClass": "alignCenter",
				"sClass": "alignRight" 
			}, {
				"mDataProp" : "totalInvoiceAmount",
				"fnRender" : function(obj) {
					var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalInvoiceAmount);
					
					return om;
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "invoiceSubmittedDate","sClass": "alignCenter",
				"sType" : "date",
				"fnRender" : function(obj) {

					return format_date(obj.aData.invoiceSubmittedDate);
				},
				"bUseRendered" : false
			},

			{
				"mDataProp" : "purchaseOrderNumber","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var onum = obj.aData.purchaseOrderNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			},  {
				"mDataProp" : "invStatus","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = obj.aData.invStatus;
					
					if(isEmptyString(om) || om == G_STATUS_MAP["INV_STATUS_NEW"]){
						om = "Received"
					}else if(om == G_STATUS_MAP["INV_STATUS_ACCEPTED"]){
						om = "Accepted";
					}else if(om == G_STATUS_MAP["INV_STATUS_REJECTED"]){
						om = "Rejected";
					}else if(om == G_STATUS_MAP["INV_STATUS_FAILED"]){
						om = "Failed";
					}else if(om == G_STATUS_MAP["INV_STATUS_FULLY_PAID"]){
						om = "Fully Paid";
					}else if(om == G_STATUS_MAP["INV_STATUS_PARTIALLY_PAID"]){
						om = "Partially Paid";
					}else {
						om = "Status not Available."
					}
					
					return om;
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "invoiceVersion","sClass": "alignCenter",
				"fnRender" : function(obj) {
					return "Show Payment Info in this column";
				},
				"bUseRendered" : false
			} ]
		});
	}

	function init_cmemosent() {
		var dwrCallMetaData = {
			callback : success_fetchcmemosecd,
			exceptionHandler : ysn_dwrerror_handler,
			timeout : 100000,
			errorHandler : ysn_dwrerror_handler
		};

		DWR_Invoice.fetchCreditMemoSent(usrcomp_comapnyId, dwrCallMetaData);
	}

	var cmemo_sent_cache = null;
	function success_fetchcmemosecd(dwrresp) {

		if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
			cmemo_sent_cache = dwrresp.objRespOrError;
			sc_process_vars.cm_sent_status = "0";
		}else{
			cmemo_sent_cache = [];
			sc_process_vars.cm_sent_status = "1";
		}
		
		render_jqcmemosenttable();
	}
	
	var ctx_cmemosent_table = null;
	function render_jqcmemosenttable() {
		ctx_cmemosent_table = jQuery('#ctx_sc_cm_sent_tbl').dataTable({
			"bProcessing" : true,
			"aaData" : cmemo_sent_cache,
			"bJQueryUI" : true,
			"bSortClasses" : false,
			"aoColumns" : [ {
				"mDataProp" : "creditMemoNumber","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var onum = obj.aData.creditMemoNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "creditMemoToCompanyName","sClass": "alignCenter",
			},

			 {
				"mDataProp" : "totalCreditMemoAmount","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalCreditMemoAmount);
					
					return om;
				},
				"bUseRendered" : false
			},{
				"mDataProp" : "creditMemoSubmittedDate","sClass": "alignCenter",
				"sType" : "date",
				"fnRender" : function(obj) {

					return format_date(obj.aData.creditMemoSubmittedDate);
				},
				"bUseRendered" : false
			}, {
				"mDataProp" : "invoiceNumber","sClass": "alignCenter",
				"sType" : "date",
				"fnRender" : function(obj) {

					var onum = obj.aData.invoiceNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			},  {
				"mDataProp" : "cmStatus","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = obj.aData.cmStatus;
					
					if(isEmptyString(om) || om == G_STATUS_MAP["CMO_STATUS_NEW"]){
						om = "Received"
					}else if(om == G_STATUS_MAP["CMO_STATUS_ACCEPTED"]){
						om = "Accepted";
					}else if(om == G_STATUS_MAP["CMO_STATUS_REJECTED"]){
						om = "Rejected";
					}else if(om == G_STATUS_MAP["CMO_STATUS_FAILED"]){
						om = "Failed";
					}else {
						om = "Status not Available."
					}
					
					return om;
				},
				"bUseRendered" : false
			}]
		});
	}
	
	function init_pmtreceived() {
		
			var dwrCallMetaData = {
					callback : success_fetchpmtrecd,
					exceptionHandler : ysn_dwrerror_handler,
					timeout : 100000,
					errorHandler : ysn_dwrerror_handler
				};
			
		
			
			DWR_Invoice.fetchPaymentsReceived(usrcomp_comapnyId,dwrCallMetaData);
		
	}
	
	var pmt_recd_cache = null;
	function success_fetchpmtrecd(dwrresp){
		
		if(dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0){
			pmt_recd_cache = dwrresp.objRespOrError;
			sc_process_vars.pmt_recd_status = "0";
		}else{
			pmt_recd_cache = [];
			sc_process_vars.pmt_recd_status = "1";
		}
		
		render_jqpmtrecdtable();
	}
	
	var ctx_pmtrecd_table = null;
	function render_jqpmtrecdtable() {
		ctx_pmtrecd_table = jQuery('#ctx_sc_pmt_recd_tbl').dataTable({
			"bProcessing" : true,
			"aaData" : pmt_recd_cache,
			"bJQueryUI" : true,
			"bSortClasses" : false,
			"aoColumns" :  [ {
				"mDataProp" : "paymentNumber","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var onum = obj.aData.paymentNumber;

					return "<a href='javascript:void(0);'>" + onum + "</a>";
				},
				"bUseRendered" : false
			},
			 {
				"mDataProp" : "paymentFromCompanyName","sClass": "alignCenter"
			},  {
				"mDataProp" : "totalPaymentAmount","sClass": "alignCenter",
				"fnRender" : function(obj) {
					var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalPaymentAmount);
					
					return om;
				},
				"bUseRendered" : false
			},{
				"mDataProp" : "paymentType","sClass": "alignCenter",
			},{
				"mDataProp" : "paymentVersion","sClass": "alignCenter",
				"fnRender" : function(obj) {
					return "Show Payment Sent To in this column";
				},
				"bUseRendered" : false
			} 

			 ]
		});
	}
	
function showNewInvScreen(){
	hideAllScreen();
	jQuery('#invContainer').addClass('show').removeClass('hide');
	render_jqLineItemTableForInv();
	
	
}

var calleeFieldForSerachBuyer = null;
function showSearchWindow(inputObj){
	render_jqSearchBuyer();
	render_jqPOTable()
	calleeFieldForSerachBuyer = inputObj;
	
	
	var dialog = jQuery('#ctx_supplier_search_buyer_tbl_div').dialog({
		autoOpen: false,
		title: 'Search in Preferred Buyer',
		 height: 400,
		 width:400
	});
	dialog.dialog('open');
	return false;
}



function this_selectBuyer(){
	var rdos = jQuery("input[name='compsuppGrp']");
	var l = rdos.length;
	var c = false;
	for(var s=0;s<l;s++){
		if(rdos[s].checked){
			var buyId = rdos[s].id.replace('compsupp','');
			c = true;
			render_buyer(buyId);
			break;
		}
	}
	
	if(!c){showusrmessage("Please select Buyer.");}
		
}



function render_buyer(suppId){
	if(comp_preferred_cache != null && comp_preferred_cache.length > 0){
		var comp = null;
		for(var i=0;i<comp_preferred_cache.length;i++){
			if(suppId == comp_preferred_cache[i].companyId){
				comp = comp_preferred_cache[i];
				break;
			}
		}
		jQuery('#ctx_supplier_search_po_tbl_div').dialog('close');
		
		if(comp != null){
			//Show Supplier name
			//dwr.util.setValue(calleeFieldForSerachBuyer,comp.companyName);
		}else{
			showusrmessage("You've no preferred suppliers. Please add supplier(s) from Profile > Supplier Management");
		}
}
}



function render_jqSearchBuyer() {
	ctx_buyer_searchSupplier = jQuery('#ctx_supplier_search_buyer_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : comp_preferred_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"bRetrieve" : true,
		
		
		"aoColumns" : [
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				return "<input type='radio' id='compsupp"+ obj.aData.companyId +"' name='compsuppGrp'>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : "companyName",
			"sClass": "alignCenter",
			"bSortable": false,
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sType" : "date",
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				if(isEmptyString(obj.aData.companyDoingBusinessAs) && isEmptyString(obj.aData.companyDomain)){
					return 'Not Available';
				}else if(!isEmptyString(obj.aData.companyDoingBusinessAs)){
					return obj.aData.companyDoingBusinessAs;
				}else if(!isEmptyString(obj.aData.companyDomain)){
					return obj.aData.companyDomain;
				}
				return 'Not Available';
			},
			"bUseRendered" : false
		}		
		
		]
	});
}


var ctx_supplier_searchPO = null;





var liCounter = 0;
function render_jqLineItemTableForInv() {
	

	
	ctx_buyer_LItable = jQuery('#ctx_supplier_line_item_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : {},
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"bFilter": false,
		"bPaginate": false,
		 "bRetrieve":true,
		
		"aoColumns" : [
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				return "<input type='checkbox' >";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {  
				liCounter ++;
				return liCounter;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sType" : "date",
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) { return "";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<input type='text' size='10' class='textbox'>";},
			"bUseRendered" : false
		},{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "";},
			"bUseRendered" : false
			
		}

		
	
		
		
		]
	});
	
	jQuery('#ctx_supplier_line_item_tbl').prev().remove();
	jQuery('#ctx_supplier_line_item_tbl').next().remove();
	
	//jQuery('#ctx_supplier_line_item_tbl').dataTable().fnAddData([false,'1',"","","","","",""]);
	
	jQuery('#ctx_supplier_line_item_tbl tbody tr').live('click', function (event) {        
	    var aData = ctx_buyer_LItable.fnGetData(this); // get datarow
	    var isRowSelected = jQuery(jQuery(this).find("td:first")).children()[0].checked; 
	    
	    if (isRowSelected)  // null if we clicked on title row
	    {
	    	jQuery(this).addClass('row_selected');
	    } else{
	    	jQuery(this).removeClass('row_selected');
	    }
	});

}
	
	